package com.suke.czx.modules.wx.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.suke.czx.common.utils.DateUtils;
import com.suke.czx.common.utils.JsonResult;
import com.suke.czx.modules.wx.cons.Constant;
import com.suke.czx.modules.wx.util.CodeUtil;
import com.suke.czx.modules.wx.vo.UserReadDays;
import com.suke.czx.modules.wxadmin.entity.DkCourseEntity;
import com.suke.czx.modules.wxadmin.entity.DkDisEntity;
import com.suke.czx.modules.wxadmin.entity.DkDomianEntity;
import com.suke.czx.modules.wxadmin.entity.DkReadPlanEntity;
import com.suke.czx.modules.wxadmin.entity.DkResourceEntity;
import com.suke.czx.modules.wxadmin.entity.DkUserEntity;
import com.suke.czx.modules.wxadmin.service.DkCourseService;
import com.suke.czx.modules.wxadmin.service.DkDisService;
import com.suke.czx.modules.wxadmin.service.DkDomianReadService;
import com.suke.czx.modules.wxadmin.service.DkDomianService;
import com.suke.czx.modules.wxadmin.service.DkReadPlanService;
import com.suke.czx.modules.wxadmin.service.DkResourceService;
import com.suke.czx.modules.wxadmin.service.DkUserService;

import me.chanjar.weixin.mp.bean.result.WxMpUser;

@RestController
@RequestMapping("/wx/course/{appid}")
public class WxCourseConntller extends BaseController{
	
	@Autowired
	private DkUserService dkUserService;
	@Autowired
	private DkResourceService dkResourceService;
	@Autowired 
	private DkReadPlanService dkReadPlanService;
	@Autowired
	private DkCourseService dkCourseService;
	@Autowired
	private DkDisService dkDisService;
	
	@Autowired 
	private DkDomianService dkDomianService;
	
	
	
	
	
	@RequestMapping(value="/course")
	public String course(@PathVariable String appid , @RequestParam(defaultValue="1")Integer cid,@RequestParam(defaultValue="1")String dis){
		DkCourseEntity dc  = dkCourseService.queryObject(cid);
		if(!dis.equals("1")){
			DkDisEntity dkdis =dkDisService.queryObject(dis);
			if(null!=dkdis){
				dc.setPriceOff(dkdis.getDisPrice());
			}
		}
		return new JsonResult(200,"ok",dc).toJson();
	}
	
	
	
	@RequestMapping(value="/resource_list")
	public String resource_list(){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", 1);
		params.put("limit", 1000);
		List<DkResourceEntity> list = dkResourceService.queryList(params);
		return new JsonResult(200,"ok",list).toJson();
	}
	

	@RequestMapping(value="/resource_detail")
	public String resource_detail( Integer id){
		return new JsonResult(200,"ok",dkResourceService.queryObject(id)).toJson();
	}
	
	
	@RequestMapping(value="/read")
	public String read(@PathVariable String appid,String dateStr ,String openid){
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if(null==wxMpUser){
			return new JsonResult(24,"用户未登录，请先登录！").toJson();
		}
		DkUserEntity dkUser = dkUserService.queryObject(wxMpUser.getOpenId());
		if(dkUser.getState()==0){
			return new JsonResult(23,"用户未订购，请跳转购买链接！").toJson();
		}
		
		
		
		if(StringUtils.isEmpty(dateStr)){
			dateStr = DateUtils.format(new Date(), DateUtils.DATE_PATTERN);
		}
		
		//获取对应天打卡情况
		Map<String,String> params1 = new HashMap<String,String>();
		params1.put("readDate", dateStr);
		params1.put("userId", dkUser.getOpenid());
		DkReadPlanEntity readPlan = dkReadPlanService.queryUserReadPlanByIdAndDate(params1);
		if(null==readPlan){
			return new JsonResult(-1,"您在今天没有阅读计划").toJson();
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", 1);
		params.put("limit", 1000);
		List<DkDomianEntity> domains  = dkDomianService.queryList(params);
		int r = (int)(Math.random()*domains.size());
    	String domain = domains.get(r).getDomainName().trim();
		String url = "https://"+domain;
		//获取当天阅读数据
		DkResourceEntity dr =  dkResourceService.queryObject(readPlan.getResourceId());
		dr.setShareTitle(dr.getShareTitle());
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("resource", dr);
		result.put("read_plan", readPlan);
		result.put("domain", url);
		return new JsonResult(200,"ok",result).toJson();
	}
	
	
	@RequestMapping(value="/plan/index")
	public String planIndex(@PathVariable String appid,String openid){
		WxMpUser wxMpUser = (WxMpUser) getSession().getAttribute(Constant.WX_USER);
		if(null==wxMpUser){
			return new JsonResult(24,"用户未登录，请先登录！").toJson();
		}
		List<DkReadPlanEntity> list = dkReadPlanService.queryUserReadPlanById(wxMpUser.getOpenId());
		
		if(null==list||list.size()==0){
			return new JsonResult(23,"用户未订购，请跳转购买链接！").toJson();
		}
		
		String todayShareTitle = "";
		
		StringBuffer read = new StringBuffer();
    	StringBuffer unread = new StringBuffer();
    	StringBuffer fillRead = new StringBuffer();
    	int readCount = 0;
    	int unreadCount = 0;
    	String today = DateUtils.getDate(new Date(),0);
    	String tomorrowDate = DateUtils.getDate(new Date(),1);
    	for(DkReadPlanEntity urp : list) {
    		if (tomorrowDate.equals(urp.getReadDate())) {
    			break;
    		}
    		if(today.equals(urp.getReadDate())){
    			todayShareTitle = dkResourceService.queryObject(urp.getResourceId()).getShareTitle();
    		}
    		if(urp.getStatus() == 0) {
    			unreadCount++;
				unread.append(urp.getReadDate()).append(",");
    		} else {
    			readCount++;
				read.append(urp.getReadDate()).append(",");
    		}
    	}
    	//System.out.println(list.get(0).getReadDate());
    	if (read.length() > 0) read.deleteCharAt(read.length()-1);
    	if (unread.length() > 0) unread.deleteCharAt(unread.length()-1);
    	
//    	if(todayShareTitle.isEmpty()){
//    		todayShareTitle = dkResourceService.queryTodayShareTitle(wxMpUser.getOpenId());
//    	}
    	
    	Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", 1);
		params.put("limit", 1000);
		
		List<DkDomianEntity> domains  = dkDomianService.queryList(params);
		int r = (int)(Math.random()*domains.size());
    	String domain = domains.get(r).getDomainName().trim();
    	String url = "http://"+domain;
    	
    	String str = "{\"read\":\""+ read.toString() 
    	+ "\",\"unread\":\"" + unread.toString() 
    	+ "\",\"fillRead\":\"" + fillRead.toString() 
    	+ "\",\"todayShareTitle\":\"" + todayShareTitle
    	+ "\",\"unreadDays\":" + unreadCount 
    	+ ",\"dayIndex\":" + readCount 
    	+ ",\"domain\":\"" + url 
    	+ "\",\"readClass\":23,\"today\":\"" + today + "\" }";
		
    	JSONObject object = JSONObject.parseObject(str);
    	
		
		return new JsonResult(200,"ok",object).toJson();
	}
	
	@RequestMapping(value="/plan/dk")
	public String planDk(@PathVariable String appid,String openid){
		if(StringUtils.isEmpty(openid)){
			return new JsonResult(-1,"openid不能为空").toJson(); 
		}
		try {
			String dateStr = DateUtils.format(new Date(), DateUtils.DATE_PATTERN);
			//获取对应天打卡情况
			Map<String,String> params1 = new HashMap<String,String>();
			params1.put("readDate", dateStr);
			params1.put("userId", openid);
			DkReadPlanEntity readPlan = dkReadPlanService.queryUserReadPlanByIdAndDate(params1);
			if(null==readPlan){
				return new JsonResult(-1,"您在今天没有打卡计划").toJson();
			}
			if(readPlan.getStatus()==1){
				return new JsonResult(200,"今天您已经完成打卡啦！").toJson(); 
			}
			if(readPlan.getStatus()==0){
				readPlan.setReadtime(new Date());
				readPlan.setStatus(1);
				dkReadPlanService.update(readPlan);
			}
			//通过打卡处理用户付款问题
			//1、检查用户是否已经分组
			
			
			
			
			return new JsonResult(200,"打卡成功").toJson(); 
			
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(-1,"打卡失败").toJson(); 
		}
	}
	
	@RequestMapping(value="/share")
	public String share(@PathVariable String appid,String openid){
		try {
			if(StringUtils.isEmpty(openid)){
				return new JsonResult(-1,"openid不能为空").toJson(); 
			}
			UserReadDays readDays = dkReadPlanService.getUserReadDays(openid);
			return new JsonResult(200,"ok",readDays).toJson(); 
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(-1,"分享页面数据查询失败").toJson(); 
		}
	}

}
